// src/hooks/useRouteMeta.js
import { useLocation, matchPath } from 'react-router-dom';
import { routes } from '@/router/index';
import type { AppRouteObject } from '@/router/type';
// 扩展 RouteObject 接口以支持 meta 属性
// declare module 'react-router-dom' {
//   interface IndexRouteObject {
//     meta?: Record<string, string | boolean | object>;
//   }
//   interface NonIndexRouteObject {
//     meta?: Record<string, string | boolean | object>;
//   }
// }
/**
 * 自定义 Hook：获取当前路由的 meta 元数据
 * @returns {Object} 当前路由的 meta 配置（默认空对象）
 */
export function useRouteMeta(): NonNullable<AppRouteObject['meta']> {
  const location = useLocation();
  const currentPath = location.pathname;

  const findMatchedRoute = (routeList: AppRouteObject[]): AppRouteObject | null => {

    for (const route of routeList) {
      const isMatched = route.path && matchPath(
        route.path,
        currentPath
      );

      if (isMatched) {
        if (route.children?.length) {
          const matchedChild = findMatchedRoute(route.children);
          return matchedChild || route;
        }
        return route;
      }

      if (route.children?.length) {
        const matchedChild = findMatchedRoute(route.children);
        if (matchedChild) return matchedChild;
      }
    }
    return null;
  };

  const matchedRoute = findMatchedRoute(routes);
  return (matchedRoute?.meta || { title: '默认标题' }) as NonNullable<AppRouteObject['meta']>;
}